package com.example.pungolo.journal.model;

import java.io.File;

import com.example.pungolo.journal.MainActivity;
import android.database.sqlite.SQLiteDatabase;

public class DiaryIO {
  
  private DiaryIO() { }
  private static DiaryDatabase diarydb;
  
  public static DiaryDatabase getDatabase() {
    if (diarydb == null)
      synchronized (DiaryDatabase.class) {
        if (diarydb == null)
          diarydb = new DiaryDatabase(getDiaryDatabase());
      }
    return diarydb;
  }
  
  public static void deleteDatabase() {
    if (diarydb != null)
      synchronized (DiaryDatabase.class) {
        if (diarydb != null) {
          diarydb.closeDb();
          diarydb = null;
          File dbfile = getDatabaseFile();
          if (dbfile.exists())
            if (!dbfile.delete())
              throw new RuntimeException("Couldn't delete old Database file.");
        }
      }
  }

  public static void resetDb() {
    deleteDatabase();
    getDiaryDatabase();
  }
  
  public static File getDiaryDirectory() {
    File f = android.os.Environment.getExternalStorageDirectory();
    f = new File(f, "Android/data/" + MainActivity.class.getPackage().getName() + "/files");
    return f;
  }
  
  private static SQLiteDatabase getDiaryDatabase() {
    File dbfile = getDatabaseFile();
    boolean existed = dbfile.exists();
    SQLiteDatabase db = SQLiteDatabase.openOrCreateDatabase(dbfile, null);
    if (!existed)
      createTables(db);
    return db;
  }

  private static File getDiaryPagesDirectory() {
    File dir = getDiaryDirectory();
    if (!dir.exists()) {
      if (!dir.mkdirs())
        throw new RuntimeException("Couldn't create the diary directory.");
    } else if (dir.isFile())
      throw new RuntimeException("The diary directory isn't a directory.");
    return dir;
  }
  
  private static File getDatabaseFile() {
    File dir = getDiaryPagesDirectory();
    File dbfile = new File(dir, "diary.db");
    return dbfile;
  }
  
  private static void createTables(SQLiteDatabase db) {
    db.beginTransaction();
    try {
      db.execSQL(
          "CREATE TABLE pages (             " +
          "  day INTEGER PRIMARY KEY,       " +
          "  image TEXT,                    " +
          "  cropl INTEGER NOT NULL,        " +
          "  cropt INTEGER NOT NULL,        " +
          "  cropr INTEGER NOT NULL,        " +
          "  cropb INTEGER NOT NULL)        ");
      db.execSQL(
          "CREATE TABLE entries (           " +
          "  datetime INTEGER PRIMARY KEY,  " +
          "  text TEXT NOT NULL,            " +
          "  mood INTEGER NOT NULL)         ");
      db.setTransactionSuccessful();
    } finally {
      db.endTransaction();
    }
  }
}